package com.xh.jf_blog.service.impl;

import com.xh.jf_blog.bean.Token;
import com.xh.jf_blog.bean.Userinfo;
import com.xh.jf_blog.common.exception.RTException;
import com.xh.jf_blog.common.form.LoginForm;
import com.xh.jf_blog.mapper.TokenMapper;
import com.xh.jf_blog.service.TokenService;
import com.xh.jf_blog.service.UserinfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * @Author PangJunjie
 * @Date 2024/2/19/019
 */
@Service
@Transactional
public class TokenServiceImpl implements TokenService {
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private UserinfoService userinfoService;

    public String saveToken(LoginForm loginForm) {
        Userinfo userinfo = userinfoService.login(loginForm);
        if (userinfo == null) {
            throw new RTException("用户名或密码不正确！");
        }
        if (userinfo.getRole() == 1 || userinfo.getStatus() == 2) {
            throw new RTException("用户信息异常，无法登录！");
        }

        Token tokenBean = tokenMapper.getByUserinfoId(userinfo.getUserinfoId());
        if (tokenBean == null) {
            tokenBean = new Token();
            tokenBean.setUserinfoId(userinfo.getUserinfoId());
        }
        String token = DigestUtils.md5Hex(UUID.randomUUID().toString());
        tokenBean.setToken(token);
        Date date = new Date();
        date.setDate(date.getDate() + 7);
        tokenBean.setExpires(date);
        if (tokenBean.getId() == null) {
            tokenMapper.insertSelective(tokenBean);
        } else {
            tokenMapper.updateByPrimaryKeySelective(tokenBean);
        }
        return token;
    }

    public void updateTokenByUserinfoId(int userinfoId) {
        System.out.println(userinfoId);
        Token token = tokenMapper.getByUserinfoId(userinfoId);
        if (token != null) {
            token.setToken(DigestUtils.md5Hex(UUID.randomUUID().toString()));
            tokenMapper.updateByPrimaryKeySelective(token);
        }
    }
}
